//
//  BarChartVC.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 10/21/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "BarChartVC.h"
#import "folyAppDelegate.h"

@implementation BarChartVC
{
    int year;
    CGFloat yMax;
}

CGFloat const CPDBarWidth = 0.4f;
CGFloat const CPDBarInitialX = 0.25f;

@synthesize hostView    = hostView_;
@synthesize aaplPlot    = aaplPlot_;
@synthesize googPlot    = googPlot_;
@synthesize priceAnnotation = priceAnnotation_;
@synthesize imvExpense;
@synthesize imvIncome;
@synthesize imvLegend;
@synthesize viewChange;
@synthesize lbYear;
@synthesize viewDetail;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    imvLegend.layer.borderWidth = 1.f;
    imvLegend.layer.cornerRadius = 10.f;
   
    [self.viewChange setFrame:CGRectMake(0, -45, 320, 44)];
    [self.view addSubview:self.viewChange];
    [self.viewChange bringSubviewToFront:self.view];
    
    [self refreshYear];
    
    self.viewDetail.layer.borderWidth = 1.0f;
    self.viewDetail.layer.cornerRadius = 5.0f;
    self.viewDetail.layer.borderColor = [UIColor blackColor].CGColor;
}

- (void)viewDidUnload
{
    [self setImvExpense:nil];
    [self setImvIncome:nil];
    [self setImvLegend:nil];
    [self setViewChange:nil];
    [self setLbYear:nil];
    [self setViewDetail:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.hostView.hostedGraph reloadData];
    [self initPlot];
    [super viewWillAppear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
    if ((fieldEnum == CPTBarPlotFieldBarTip) && (index < [[[CPDStockPriceStore sharedInstance] datesInWeek] count])) {
        if ([plot.identifier isEqual:CPDTickerSymbolAAPL]) {
            return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL] objectAtIndex:index];
        } else if ([plot.identifier isEqual:CPDTickerSymbolGOOG]) {
            return [[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG]objectAtIndex:index];            
        } 
    }
    return [NSDecimalNumber numberWithUnsignedInteger:index];    
}

#pragma mark - CPTBarPlotDelegate methods
-(void)barPlot:(CPTBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index {
    // 1 - Is the plot hidden?
    if (plot.isHidden == YES) {
        return;
    }
    // 2 - Create style, if necessary
    CPTMutableTextStyle *style = nil;
    if (!style) {
        style = [CPTMutableTextStyle textStyle];    
        
        style.fontSize = 12;
        style.fontName = @"Helvetica-Bold";        
    }
    // 3 - Create annotation, if necessary
    NSNumber *price = [self numberForPlot:plot field:CPTBarPlotFieldBarTip recordIndex:index];
    
    if([price floatValue] == 0.0f)
    {
        NSLog(@"PRICE = %f", [price floatValue]);
        return;
    }
    
    if (!self.priceAnnotation) {
        NSNumber *x = [NSNumber numberWithInt:0];
        NSNumber *y = [NSNumber numberWithInt:0];
        NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
        self.priceAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];        
    }
    // 4 - Create number formatter, if needed
    NSNumberFormatter *formatter = nil;
    if (!formatter) {
        formatter = [[NSNumberFormatter alloc] init];
        [formatter setMaximumFractionDigits:2];        
    }
    // 5 - Create text layer for annotation
    NSString *priceValue = [formatter stringFromNumber:price];
    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:priceValue style:style];
    //NSLog(@"LAYER = %@", textLayer);
    
    self.priceAnnotation.contentLayer = textLayer;
    // 6 - Get plot index based on identifier
    NSInteger plotIndex = 0;
    if ([plot.identifier isEqual:CPDTickerSymbolAAPL] == YES) {
        plotIndex = 0;
        style.color= [CPTColor greenColor];
    } else if ([plot.identifier isEqual:CPDTickerSymbolGOOG] == YES) {
        plotIndex = 1;
        style.color= [CPTColor redColor];
    } else if ([plot.identifier isEqual:CPDTickerSymbolMSFT] == YES) {
        plotIndex = 2;
    }
    // 7 - Get the anchor point for annotation
    CGFloat x = index + CPDBarInitialX + (plotIndex * CPDBarWidth); 
    NSNumber *anchorX = [NSNumber numberWithFloat:x];    
    CGFloat y = [price floatValue] + yMax / 30;
    NSNumber *anchorY = [NSNumber numberWithFloat:y];    
    self.priceAnnotation.anchorPlotPoint = [NSArray arrayWithObjects:anchorX, anchorY, nil]; 
    // 8 - Add the annotation 
    [plot.graph.plotAreaFrame.plotArea addAnnotation:self.priceAnnotation];
}

#pragma mark - BarPlot Datasource
-(NSString *)legendTitleForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSUInteger)index
{
    return @"N/A";
}

#pragma mark - Chart behavior
-(void)initPlot {
    self.hostView.allowPinchScaling = NO;
    [self configureGraph];
    [self configurePlots];
    [self configureAxes]; 
}

-(void)configureGraph {
    // 1 - Create the graph
    CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
    graph.plotAreaFrame.masksToBorder = NO;
    self.hostView.hostedGraph = graph;    
    // 2 - Configure the graph    
    //[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
    [graph applyTheme:[CPTTheme themeNamed:kCPTPlainWhiteTheme]];
    graph.paddingBottom = 25.f;      
    graph.paddingLeft  = 30.f;
    graph.paddingTop    = 20.f;
    graph.paddingRight  = 10.f;
    // 3 - Set up styles
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
    titleStyle.color = [CPTColor blackColor];
    titleStyle.fontName = @"Helvetica-Bold";
    titleStyle.fontSize = 12.0f;
    // 4 - Set up title
    int year1 = ((folyAppDelegate *)[[UIApplication sharedApplication] delegate]).currentYear;
    NSString *title = [NSString stringWithFormat: @"Income/Expense in %i",year1];
    graph.title = title;  
    graph.titleTextStyle = titleStyle;
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
    // 5 - Set up plot space
    CGFloat xMin = 0.0f;
    CGFloat xMax = [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
    CGFloat yMin = 0.0f;
    
    //CGFloat yMax = 800;  // should determine dynamically based on max price
    CGFloat y1 = [self maxInArray:[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolAAPL]];
    CGFloat y2 = [self maxInArray:[[CPDStockPriceStore sharedInstance] weeklyPrices:CPDTickerSymbolGOOG]];
    yMax = y2;
    if(y1 > y2)
    {
        yMax = y1;
    }
    if(yMax > 100)
    {
        yMax += yMax*0.1;
        CGFloat yN = roundf(yMax/10);
        yMax = (yN +1) * 10;
    }
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(xMin) length:CPTDecimalFromFloat(xMax)];
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(yMin) length:CPTDecimalFromFloat(yMax)];
    
}

-(void)configurePlots {
    // 1 - Set up the three plots
    self.aaplPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor greenColor] horizontalBars:NO];
    self.aaplPlot.identifier = CPDTickerSymbolAAPL;
    self.googPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    self.googPlot.identifier = CPDTickerSymbolGOOG;
    //    self.msftPlot.identifier = CPDTickerSymbolMSFT;
    // 2 - Set up line style
    CPTMutableLineStyle *barLineStyle = [[CPTMutableLineStyle alloc] init];
    barLineStyle.lineColor = [CPTColor lightGrayColor];
    barLineStyle.lineWidth = 0.5;
    // 3 - Add plots to graph
    CPTGraph *graph = self.hostView.hostedGraph;
    CGFloat barX = CPDBarInitialX;
    //    NSArray *plots = [NSArray arrayWithObjects:self.aaplPlot, self.googPlot, self.msftPlot, nil];
    NSArray *plots = [NSArray arrayWithObjects:self.aaplPlot, self.googPlot, nil];
    for (CPTBarPlot *plot in plots) {
        plot.dataSource = self;
        plot.delegate = self;
        plot.barWidth = CPTDecimalFromDouble(CPDBarWidth);
        plot.barOffset = CPTDecimalFromDouble(barX);
        plot.lineStyle = barLineStyle;
        [graph addPlot:plot toPlotSpace:graph.defaultPlotSpace];
        barX += CPDBarWidth;
    }
}

-(void)configureAxes {
    // 1 - Configure styles
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor blackColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 12.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 2.0f;
    axisLineStyle.lineColor = [[CPTColor blackColor] colorWithAlphaComponent:1];
    
    // 2 - Get the graph's axis set
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *) self.hostView.hostedGraph.axisSet;
    // 3 - Configure the x-axis
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];  
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    
    axisSet.xAxis.labelTextStyle = axisTitleStyle;
    axisSet.xAxis.labelFormatter = formatter;
    axisSet.xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    
//    axisSet.xAxis.title = @"Months of Year (1 - 12)"; 
//    axisSet.xAxis.titleTextStyle = axisTitleStyle;    
//    axisSet.xAxis.titleOffset = 5.0f;
    
    axisSet.xAxis.axisLineStyle = axisLineStyle;
    axisSet.xAxis.majorTickLineStyle = axisLineStyle;
    axisSet.xAxis.majorTickLength = 5.0f;
    axisSet.xAxis.tickDirection = CPTSignNegative;
    
    CGFloat monthCount = [[[CPDStockPriceStore sharedInstance] datesInWeek] count];
    NSMutableSet *xLabels = [NSMutableSet setWithCapacity:monthCount];
    NSMutableSet *xLocations = [NSMutableSet setWithCapacity:monthCount]; 
    CGFloat i = 0.5f;
    for (NSString *month in [[CPDStockPriceStore sharedInstance] datesInWeek]) {
        CPTAxisLabel *label = [[CPTAxisLabel alloc] initWithText:month  textStyle:axisTitleStyle];
        CGFloat location = i++;
        label.tickLocation = CPTDecimalFromCGFloat(location);
        label.offset = axisSet.xAxis.majorTickLength;
        if (label) {
            [xLabels addObject:label];
            [xLocations addObject:[NSNumber numberWithFloat:location]];                        
        }
    }
    axisSet.xAxis.axisLabels = xLabels;
    axisSet.xAxis.majorTickLocations = xLocations;

    
    // 4 - Configure the y-axis
    axisSet.yAxis.labelingPolicy = CPTAxisLabelingPolicyEqualDivisions;
    axisTitleStyle.fontSize = 10.0f;
    axisSet.yAxis.labelTextStyle = axisTitleStyle;
    axisSet.yAxis.labelRotation = M_PI/3;
    axisSet.yAxis.labelAlignment = CPTAlignmentRight;
    
    axisSet.yAxis.title = @"Amount";
    axisTitleStyle.fontSize = 12.0f;
    axisSet.yAxis.titleTextStyle = axisTitleStyle;
    axisSet.yAxis.titleOffset = 5.0f;      
    axisSet.yAxis.axisLineStyle = axisLineStyle;
    
}

-(void)hideAnnotation:(CPTGraph *)graph {
}

#pragma mark - IBAction

-(IBAction)backPreviousView:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)changeTime:(id)sender {
    [self showChange];
}
- (IBAction)increaseYear:(id)sender {
    
    year ++;
    lbYear.text = [NSString stringWithFormat:@"%i", year];
    
}
- (IBAction)decreaseYear:(id)sender {
    year --;
    lbYear.text = [NSString stringWithFormat:@"%i", year];
}
- (IBAction)OK:(id)sender {
   ((folyAppDelegate *)[[UIApplication sharedApplication] delegate]).currentYear = year;

    [self hideChange];

    self.priceAnnotation = nil;
    [self.hostView.hostedGraph reloadData];
    [self initPlot];
}

#pragma mark - Extra Method
-(void)showChange
{
    
    CGRect changeFrame = [self.viewChange frame];
    changeFrame.origin.x = 0;
    changeFrame.origin.y = 0;
    
    [UIView beginAnimations:@"push_animation" context:NULL];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    [self.viewChange setFrame:changeFrame];
    
    [UIView commitAnimations];
}

-(void)hideChange
{
    CGRect changeFrame = [self.viewChange frame];
    changeFrame.origin.x = 0;
    changeFrame.origin.y = -45;
    
    [UIView beginAnimations:@"push_animation" context:NULL];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    [self.viewChange setFrame:changeFrame];
    
    [UIView commitAnimations];
}

-(void)refreshYear
{
    year = ((folyAppDelegate *)[[UIApplication sharedApplication] delegate]).currentYear;
    lbYear.text = [NSString stringWithFormat:@"%i", year];
}

-(CGFloat)maxInArray: (NSArray *)array
{
    CGFloat max = [[array objectAtIndex:0] floatValue];
    for(id i in array)
    {
        if([i floatValue] > max)
        {
            max = [i floatValue];
        }
    }
    return max;
}


@end
